package com.thlws.consul.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器,Spring容器中存在实例会自动启用
 * @author HanleyTang 2019-06-11
 */
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String token = exchange.getRequest().getQueryParams().getFirst("token");

        if (token == null || token.isEmpty()) {
            log.info("全局过滤器 MyGlobalFilter 检测到token为空，拒绝继续执行.");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        log.info("全局过滤器 MyGlobalFilter 拦截到 token:{} 放行请求",token);

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -10;
    }


    /**这种方式为官方示例，直接创建了全局过滤器，功能同上*/
//    @Bean
//    @Order(-1)
//    public GlobalFilter a() {
//        return (exchange, chain) -> {
//
//            log.info("first pre filter");
//            String token = exchange.getRequest().getQueryParams().getFirst("token");
//            if (StringUtils.isEmpty(token)) {
//                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//                return exchange.getResponse().setComplete();
//            }
//
//            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
//                log.info("third post filter");
//            }));
//        };
//    }
}
